package nl.avans.osgi.hgttg.computer.internal;

import java.util.Dictionary;
import java.util.Hashtable;

import nl.avans.osgi.hgttg.answers.Answer;
import nl.avans.osgi.hgttg.answers.impl.AnswerImpl;
import nl.avans.osgi.hgttg.questions.Question;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

public class DeeperThougth implements BundleActivator, Runnable {

    private BundleContext context;
    private ServiceTracker questionTracker;
    private Thread thread;
    
	public void start(BundleContext context) throws Exception {
	    this.context = context;
	    
	    String filterString = 
	        "(&(objectClass=" + Question.class.getName() + ")" +
	    	    " (for=computer))";
        Filter filter = this.context.createFilter(filterString);
        questionTracker = new ServiceTracker(this.context, filter , null);
        questionTracker.open();
        
        thread = new Thread(this, "DeeperThougth");
        thread.start();
	}

	public void stop(BundleContext context) throws Exception {
	    questionTracker.close();
	    thread = null;
	}

    @Override
    public void run() {
        Thread current = Thread.currentThread();
        int processingCnt = 0;
        boolean processing = false;
        while (thread == current) {
            ServiceReference[] qRefs = questionTracker.getServiceReferences();
            if (!processing && qRefs != null && qRefs.length > 0) {
                processing = true;
                ServiceReference qRef = qRefs[0];
                Question question = (Question) questionTracker.getService(qRef);
                System.out.println("\nProcessing question from " + question.getQuestion());
                questionTracker.remove(qRef);
            }
            if (processing && processingCnt == 6) {
                System.out.println(" Finisched after 1.42 million year");
                Dictionary<String, String> prop = new Hashtable<String, String>();
                prop.put("for", "mice");
                Answer answer = new AnswerImpl("computer", "The answer is: OSGi \n");
                context.registerService(Answer.class.getName(), answer, prop);
                processing = false;
                processingCnt = 0;
            } else if (processing && processingCnt < 6) {
                processingCnt++;
                System.out.print(".");
            } else {
                processingCnt = 0;
                processing = false;
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {}
        }
    }
}
